<template>
  <div class="app-container">
    <el-card class="box-card">
      <div class="table">
        <div class="addUser">
          <el-button
            class="el-icon-folder-add"
            type="primary"
            @click="addDialog"
            >新增</el-button
          >
        </div>
        <el-table
          v-loading="listLoading"
          :data="tableData"
          element-loading-text="Loading"
          border
          fit
          highlight-current-row
          show-overflow-tooltip
        >
          <el-table-column align="center" type="index" label="序号">
          </el-table-column>
          <el-table-column
            label="昵称"
            align="center"
            prop="userName"
          ></el-table-column>
          <el-table-column label="手机号" align="center" prop="phone">
          </el-table-column>
          <el-table-column label="头像" align="center">
            <template slot-scope="scope">
              <el-image :src="scope.row.avatar" style="width: 80px" :preview-src-list="[scope.row.avatar]"></el-image>
            </template>
          </el-table-column>
          <el-table-column label="邮箱" align="center" prop="email">
          </el-table-column>
          <el-table-column label="地址" align="center" prop="address">
          </el-table-column>
          <el-table-column label="年龄" align="center" prop="age">
          </el-table-column>
          <el-table-column label="性别" align="center">
            <template slot-scope="scope">
              <el-tag :type="scope.row.sex === '1' ? 'success' : ''">{{
                scope.row.sex === "1" ? "男" : "女"
              }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="备注" align="center" prop="other">
          </el-table-column>
          <el-table-column align="center" label="操作" width="250">
            <template slot-scope="scope">
              <el-button
                class="el-icon-view"
                type="primary"
                size="mini"
                @click="queryInfo(scope.row)"
                >查看</el-button
              >

              <el-button
                class="el-icon-edit"
                type="warning"
                size="mini"
                @click="editDialog(scope.row)"
                >修改</el-button
              >
              <el-button
                class="el-icon-folder-delete"
                type="danger"
                size="mini"
                @click="delInfo(scope.row)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- 分页 -->
      <div class="pageBox">
        <el-pagination
          background
          layout="total, prev, pager, next"
          :page-size="pageOption.pageNum"
          :total="pageOption.total"
          :current-page="pageOption.pageSize"
          @current-change="pageJump"
          @prev-click="pageOption.pageSize--"
          @next-click="pageOption.pageSize++"
        ></el-pagination>
      </div>
      <div class="userFormData">
        <el-dialog
          :title="dialogOption.title"
          :visible.sync="dialogOption.visible"
        >
          <el-form ref="formData" :model="formData" label-width="80px">
            <el-row>
              <el-col :span="12">
                <el-form-item
                  label="手机号"
                  prop="phone"
                  :label-width="formLabelWidth"
                  :rules="formRules.required"
                >
                  <el-input
                    :readonly="dialogOption.required"
                    v-model="formData.phone"
                    autocomplete="off"
                    :disabled="dialogOption.disabled"
                  >
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item
                  label="昵称"
                  prop="userName"
                  :label-width="formLabelWidth"
                  :rules="formRules.required"
                >
                  <el-input
                    :readonly="dialogOption.required"
                    v-model="formData.userName"
                    autocomplete="off"
                    :disabled="dialogOption.disabled"
                  ></el-input>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row>
              <el-col :span="12">
                <el-form-item
                  label="性别"
                  prop="sex"
                  :label-width="formLabelWidth"
                  :rules="formRules.required"
                >
                  <el-select
                    :readonly="dialogOption.required"
                    v-model="formData.sex"
                    placeholder="请选择性别"
                    :disabled="dialogOption.disabled"
                  >
                    <el-option label="男" value="1"></el-option>
                    <el-option label="女" value="0"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item
                  label="年龄"
                  prop="age"
                  :label-width="formLabelWidth"
                  :rules="formRules.required"
                >
                  <el-input-number
                    :readonly="dialogOption.required"
                    v-model="formData.age"
                    :disabled="dialogOption.disabled"
                    :min="1"
                    :max="100"
                    label="年龄"
                  ></el-input-number>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item
                  label="邮箱"
                  prop="email"
                  :label-width="formLabelWidth"
                  :rules="formRules.required"
                >
                  <el-input
                    :readonly="dialogOption.required"
                    v-model="formData.email"
                    :disabled="dialogOption.disabled"
                    autocomplete="off"
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="地址" :label-width="formLabelWidth">
                  <el-input
                    :readonly="dialogOption.required"
                    v-model="formData.address"
                    :disabled="dialogOption.disabled"
                    autocomplete="off"
                  ></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <el-form-item label="备注" :label-width="formLabelWidth">
                  <el-input
                    :readonly="dialogOption.required"
                    type="textarea"
                    placeholder="请输入内容"
                    v-model="formData.other"
                    maxlength="30"
                    show-word-limit
                    :disabled="dialogOption.disabled"
                  >
                  </el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="头像" :label-width="formLabelWidth">
                  <el-upload
                    class="avatar-uploader"
                    :action="uploadUrl"
                    :show-file-list="false"
                    :on-success="handleAvatarSuccess"
                    :before-upload="beforeAvatarUpload"
                    :disabled="dialogOption.disabled"
                  >
                    <img
                      v-if="formData.avatar"
                      :src="formData.avatar"
                      class="avatar"
                    />
                    <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                  </el-upload>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item
                  label="角色"
                  prop="role_id"
                  :label-width="formLabelWidth"
                  :rules="formRules.required"
                >
                  <el-select
                    v-model="formData.role_id"
                    placeholder="请选择角色"
                    :disabled="dialogOption.disabled"
                    @change="SelectItemRole"
                  >
                    <el-option
                      v-for="(item, index) in roleList"
                      :key="index"
                      :label="item.roleName"
                      :value="item.id"
                    >
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="dialogOption.visible = false">取 消</el-button>
            <el-button
              type="primary"
              v-if="dialogOption.type === 1"
              @click="dialogOption.visible = false"
              >确 定</el-button
            >
            <el-button
              type="primary"
              v-if="dialogOption.type === 2"
              @click="editInfo"
              >修 改</el-button
            >
            <el-button
              class="el-icon-add"
              v-if="dialogOption.type === 3"
              type="warning"
              @click="addInfo"
              >新增</el-button
            >
          </div>
        </el-dialog>
      </div>
    </el-card>
  </div>
</template>

<script>
import {
  getUserList,
  addUserInfo,
  delUserInfo,
  editUserInfo,
} from "@/api/user";
import { getRoleList, editRoleUser } from "@/api/role";
export default {
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: "success",
        draft: "gray",
        deleted: "danger",
      };
      return statusMap[status];
    },
  },
  data() {
    return {
      // uploadUrl: "https://www.lengnuanit.top/api/upload/upload",
      uploadUrl: "http://127.0.0.1:7001/api/upload/upload",
      formLabelWidth: "100px",
      formRules: this.$store.state.settings.formRules,
      tableData: null,
      listLoading: true,
      pageOption: {
        pageNum: 10,
        pageSize: 1,
        total: 1,
      },
      dialogOption: {
        title: "查看用户",
        type: 1,
        visible: false,
        required: false,
        disabled: false,
      },
      formData: {
        userName: "",
        sex: null,
        age: null,
        phone: "",
        address: "",
        email: "",
        avatar: "",
        other: "",
        role_id: null,
      },
      userId: null,
      roleList: null,
    };
  },
  created() {
    this.getData();
  },
  methods: {
    //获取用户数据
    getData() {
      this.listLoading = true;
      getUserList({
        pageNum: this.pageOption.pageNum,
        pageSize: this.pageOption.pageSize,
      }).then((res) => {
        console.log(res);
        this.tableData = res.result.data;
        this.pageOption.total = res.result.total;
        this.listLoading = false;
      });
    },
    //获取角色数据
    getRoleListInfo() {
      getRoleList().then((res) => {
        // delete res.data[0]
        this.roleList = res.data.slice(1);
      });
    },
    //查看用户
    queryInfo(row) {
      console.log(row);
      this.resetForm("formData");
      this.getRoleListInfo();
      this.formData = JSON.parse(JSON.stringify(row));
      this.dialogOption.type = 1;
      this.dialogOption.disabled = true;
      this.dialogOption.visible = true;
      this.dialogOption.required = true;
      this.dialogOption.title = "查看用户";
    },
    //新增弹窗
    addDialog() {
      this.resetForm("formData");
      this.formData = {};
      this.getRoleListInfo();
      this.dialogOption.type = 3;
      this.dialogOption.visible = true;
      this.dialogOption.required = false;
      this.dialogOption.disabled = false;
      this.dialogOption.title = "新增用户";
    },
    //新增用户
    addInfo() {
      this.$refs["formData"].validate((valid) => {
        if (valid) {
          addUserInfo(this.formData).then((res) => {
            console.log(res);
            if (res.code == 200) {
              this.$message.success(res.msg);
              this.getData();
              this.dialogOption.visible = false;
            } else {
              this.$message.error(res.msg);
            }
          });
        }
      });
    },
    //修改弹窗
    editDialog(row) {
      console.log(row);
      this.resetForm("formData");
      this.getRoleListInfo();
      this.userId = row.id;
      this.formData = JSON.parse(JSON.stringify(row));
      this.dialogOption.type = 2;
      this.dialogOption.visible = true;
      this.dialogOption.required = false;
      this.dialogOption.disabled = false;
      this.dialogOption.title = "修改用户";
    },
    //修改用户
    editInfo() {
      editUserInfo({
        id: this.userId,
        data: this.formData,
      }).then((res) => {
        console.log(res);
        if (res.code == 200) {
          this.$message.success(res.msg);
          this.getData();
        } else {
          this.$message.error(res.msg);
        }
        this.dialogOption.visible = false;
      });
    },
    //删除
    delInfo(row) {
      console.log(row);
      this.$confirm(
        "此操作将删除" + row.userName + "这条数据，是否继续？",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(() => {
          delUserInfo(row.id)
            .then((res) => {
              console.log(res);
              if (res.code == 200) {
                this.$message.success(res.msg);
                this.getData();
              } else {
                this.$message.error(res.msg);
              }
            })
            .catch({});
        })
        .catch(() => {
          this.$message.info("已取消");
        });
    },
    // 重置验证规则
    resetForm(formName) {
      // console.log(formName);
      if (this.$refs[formName] != undefined) {
        this.$refs[formName].resetFields();
      }
    },
    // 分页跳转
    pageJump(page) {
      //console.log(page);
      this.pageOption.pageSize = page;
      this.getData();
    },
    //图片上传
    handleAvatarSuccess(res, file) {
      this.$set(this.formData, "avatar", res.data.url);
      console.log(this.formData.avatar);
    },
    //图片上传
    beforeAvatarUpload(file) {
      console.log(file);
      const isType = file.type === "image/jpeg" || file.type === "image/png";
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isType) {
        this.$message.error("上传头像图片只能是 JPG或PNG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isType && isLt2M;
    },
    SelectItemRole(e) {
      console.log(e);
      editRoleUser({
        roleId: e,
        userIds: this.userId,
      }).then((res) => {
        console.log(res);
      });
    },
  },
};
</script>
<style lang="scss" scope>
.addUser {
  padding: 0 0 20px 0;
}
.pageBox {
  text-align: right;
  padding: 10px 0 20px 0;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
